<?php

namespace app\admin\model;

use think\Db;
use think\Model;

class Category extends Model
{
    protected $table = 'petct_category';

    /**
     * 获取栏目信息
     * @param $limit
     * @param $where
     * @return array
     */
    public function getCate($limit, $where)
    {
        try {

            $res = $this->where($where)
                ->order('id', 'desc')->paginate($limit);

        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, $res, 'ok');
    }

    /**
     * 增加栏目
     * @param $params
     * @return array
     */
    public function addCate($params)
    {
        try {

            $where = [
                'catname' => $params['catname']
            ];
            $flag = $this->where($where)->count();
            if ($flag) {
                return modelReMsg(-2, '', '栏目已经存在');
            }

            $params['add_time'] = date('Y-m-d H:i:s');
            if (empty($params['bname'])) {
                $params['bname'] = $params['catname'];
            }

            $this->insert($params);
        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, '', '栏目添加成功');
    }

    /**
     * 根据id获取栏目信息
     * @param $id
     * @return array
     */
    public function getCateById($id)
    {
        try {

            $info = $this->where('id', $id)->findOrEmpty()->toArray();
        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, $info, 'ok');
    }

    /**
     * 编辑栏目
     * @param $params
     * @return array
     */
    public function editCate($params)
    {
        try {

            $has = $this->where('catname', $params['catname'])
                ->where('id', '<>', $params['id'])
                ->findOrEmpty()->toArray();

            if (!empty($has)) {
                return modelReMsg(-2, '', '栏目已经存在');
            }
            $params['update_time'] = date('Y-m-d H:i:s');

            $this->save($params, ['id' => $params['id']]);
        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, '', '编辑栏目成功');
    }

    /**
     * 删除栏目
     * @param $id
     * @return array
     */
    public function delCate($id)
    {
        try {

            $this->where('id', $id)->delete();
        } catch (\Exception $e) {

            return modelReMsg(-1, '', $e->getMessage());
        }

        return modelReMsg(0, '', '删除成功');
    }
}